package south

import (
	"fmt"
	"iot-base/common/config"
	"iot-base/common/event"

	"iot-base/common/eventtype"
	mqtt "iot-base/common/mqtt"
	"iot-base/common/notify"
	"iot-base/dm/common/alarm"
)

//同步告警
func keepStepAlarm(edgeID string) {
	if !config.MQTTOption.IsMqttConnection {
		return
	}
	cmd := &mqtt.Cmd{
		CmdType: "syncAlarm",
	}
	var alarmInfo alarm.AlarmInfo

	client.SendCmd(cmd, config.GetEdgeTopic()+"sync/alarms/"+edgeID, 10, &alarmInfo, func(client mqtt.IOTMQTTBroker,
		pCmdResponse *mqtt.CmdResponse, pCmd *mqtt.Cmd) {
		if pCmdResponse.Code == 0 && pCmdResponse.Body != nil {
			pAlarm, ok := pCmdResponse.Body.(*alarm.AlarmInfo)
			if ok && pAlarm != nil {
				fmt.Println("-----------------------sync/alarms--------------------------")
				event.SyncAlarms(pAlarm.IDs, pAlarm.Alarms)
			}

		}
	}, nil)
}

//处理告警
func handleAlarm(client mqtt.IOTMQTTBroker, topic string, pCmd *mqtt.Cmd) {
	if pCmd.Body != nil {
		pAlarm, ok := pCmd.Body.(*eventtype.Alarm)
		if ok {
			if pAlarm.Flag == "END" {
				event.ThingAlarmClear(pAlarm)
			} else {
				event.ThingAlarm(pAlarm)
			}
		}
	}
}

func init() {
	// topic string, obj interface{}, fun func(t string, b interface{}))
	if !config.MQTTOption.IsMqttConnection {
		return
	}
	notify.SubMsg(true, "syncEgdeAlarm", nil, func(t string, b interface{}) {
		id, ok := b.(string)
		if ok && id != "" {
			keepStepAlarm(id)
		}
	})
}
